package com.cn.ant.modules.school.web;

import com.cn.ant.common.config.Global;
import com.cn.ant.common.persistence.Page;
import com.cn.ant.common.utils.AjaxJson;
import com.cn.ant.common.utils.DateUtils;
import com.cn.ant.common.utils.StringUtils;
import com.cn.ant.common.utils.excel.ExportExcel;
import com.cn.ant.common.utils.excel.ImportExcel;
import com.cn.ant.common.web.BaseController;
import com.cn.ant.modules.school.entity.School;
import com.cn.ant.modules.school.entity.SchoolMajor;
import com.cn.ant.modules.school.service.SchoolMajorService;
import com.cn.ant.modules.school.service.SchoolService;
import com.cn.ant.modules.score.entity.LqSchool;
import com.cn.ant.modules.sys.entity.Area;
import com.cn.ant.modules.sys.service.AreaService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学校信息Controller
 * @author AntDream
 * @version 2015-08-14
 */
@Controller
@RequestMapping(value = "${adminPath}/school/school")
public class SchoolController extends BaseController {

	@Autowired
	private SchoolService schoolService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private SchoolMajorService schoolMajorService;
	
	@ModelAttribute
	public School get(@RequestParam(required=false) String id) {
		School entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = schoolService.get(id);
		}
		if (entity == null){
			entity = new School();
		}
		return entity;
	}
	
	@RequiresPermissions("school:school:view")
	@RequestMapping(value = {"list", ""})
	public String list(School school, HttpServletRequest request, HttpServletResponse response, Model model) {
		//查询省的信息
		Map<String, String> params = new HashMap<>();
		params.put("type", "2");
		List<Area> provinceList = areaService.query(params);
		Page<School> page = schoolService.findPage(new Page<School>(request, response), school);
		model.addAttribute("page", page);
		model.addAttribute("provinceList", provinceList);
		return "modules/school/schoolList";
	}

	@RequiresPermissions("school:school:view")
	@RequestMapping(value = "form")
	public String form(School school, Model model) {
		model.addAttribute("school", school);
		//查询省的信息
        Map<String, String> params = new HashMap<>();
        params.put("type", "2");
        List<Area> provinceList = areaService.query(params);
        model.addAttribute("provinceList", provinceList);
        return "modules/school/schoolForm";
	}

    /**
     * 学校-专业配置
     * @param school
     * @param model
     * @return
     */
    @RequiresPermissions("school:school:edit")
    @RequestMapping(value = "marjorSettingForm")
    public String marjorSettingForm(School school, Model model) {
		//查询学校对应的专业
		SchoolMajor schoolMajor = new SchoolMajor();
		schoolMajor.setSchoolCode(school.getSchoolCode());
		List<SchoolMajor> schoolMajorList =  schoolMajorService.findList(schoolMajor);
		school.setSchoolMajorList(schoolMajorList);
		return "modules/school/schoolMajorInfo";
	}

	@RequiresPermissions("school:school:edit")
	@RequestMapping(value = "lqForm")
	public String lqForm(School school, Model model) {
		LqSchool lqSchool = new LqSchool();
		lqSchool.setSchoolCode(school.getSchoolCode());
		lqSchool.setSchoolName(school.getSchoolName());
		//查询省的信息
		Map<String, String> params = new HashMap<>();
		params.put("type", "2");
		List<Area> provinceList = areaService.query(params);
		model.addAttribute("provinceList", provinceList);
		model.addAttribute("lqSchool", lqSchool);
		return "modules/score/lqSchoolForm";
	}

	@RequiresPermissions("school:school:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public AjaxJson save(School school, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
        AjaxJson result = new AjaxJson();
        try {
            if (!beanValidator(model, school)) {
                result.setSuccess(false);
                result.setMsg("数据校验失败,请重试");
                return result;
            }
            schoolService.save(school);
            result.setSuccess(true);
            result.setMsg("保存学校成功");
        } catch (Exception e) {
            e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("系统异常,保存学校失败");
        }
        return result;
	}

	@RequiresPermissions("school:school:edit")
	@RequestMapping(value = "saveMajor")
	@ResponseBody
	public AjaxJson saveMajor(School school, Model model, HttpServletRequest request) {
		AjaxJson result = new AjaxJson();
		try {
            schoolMajorService.save(school);
            result.setSuccess(true);
            result.setMsg("保存学校专业成功");
        } catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("系统异常，保存学校专业失败");
		}
		return result;
	}

	@RequiresPermissions("school:school:edit")
	@RequestMapping(value = "delete")
	public String delete(School school, RedirectAttributes redirectAttributes) {
		schoolService.delete(school);
		addMessage(redirectAttributes, "删除学校成功");
		return "redirect:"+Global.getAdminPath()+"/school/school/?repage";
	}

	@RequiresPermissions("school:school:edit")
	@RequestMapping(value = "export", method= RequestMethod.POST)
	public String exportFle(School school,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes){
		try {
			String fileName = "学校数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Map<String, Object> params = new HashMap<String, Object>();
			Page<School> page = schoolService.findPage(new Page<School>(request, response, -1), school);
			new ExportExcel("学校数据", School.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出学校数据失败！失败信息：" + e.getMessage());
			e.printStackTrace();
		}
		return "redirect:"+Global.getAdminPath()+"/school/school/?repage";
	}

	@RequiresPermissions("school:school:edit")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "学校数据导入模板.xlsx";
			Page<School> page = schoolService.findPage(new Page<School>(1, 1), new School());
			new ExportExcel("学校数据", School.class, 2).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
			e.printStackTrace();
		}
		return "redirect:"+Global.getAdminPath()+"/school/school/?repage";
	}

	@RequiresPermissions("school:school:edit")
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public String importFile(MultipartFile file, HttpServletRequest request,RedirectAttributes redirectAttributes,Model model) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<School> list = ei.getDataList(School.class);
			//schoolService.batchSave(list);
			logger.info("导入学校成功");
			addMessage(redirectAttributes,"导入成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:"+Global.getAdminPath()+"/school/school/?repage";
	}

}